package online.heycm.platform.canary.service;

import feign.Client;
import lombok.extern.slf4j.Slf4j;
import online.heycm.platform.canary.common.CanaryProperties;
import online.heycm.platform.canary.common.CanaryRule;
import online.heycm.platform.canary.common.CanaryRuleCache;
import online.heycm.platform.common.tools.Jackson;
import online.heycm.platform.nacos.NacosConfListener;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.cloud.loadbalancer.blocking.client.BlockingLoadBalancerClient;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.List;

/**
 * 自动装配注册 OpenFeign灰度增强客户端
 *
 * @author heycm
 * @since 2023/12/30 10:00
 */
@Slf4j
@Configuration(proxyBeanMethods = false)
@EnableConfigurationProperties(CanaryProperties.class)
public class CanaryAutoConfiguration {

    public CanaryAutoConfiguration() {
        log.info("CanaryAutoConfiguration init...");
    }

    /**
     * 注册 CanaryFeignClient
     */
    @Bean
    public Client feignClient(BlockingLoadBalancerClient loadBalancerClient, DiscoveryClient discoveryClient,
                              CanaryProperties canaryProperties, NacosConfListener nacosConfListener) {
        refreshCanaryRuleCache(canaryProperties, nacosConfListener);
        return new CanaryFeignClient(new Client.Default(null, null),
                loadBalancerClient, discoveryClient);
    }

    /**
     * Nacos 灰度配置监听
     */
    private void refreshCanaryRuleCache(CanaryProperties canaryProperties, NacosConfListener nacosConfListener) {
        nacosConfListener.addListener(canaryProperties.getDataId(), canaryProperties.getGroup(), config -> {
            List<CanaryRule> rules = Jackson.toList(config, CanaryRule.class);
            CanaryRuleCache.update(rules);
        });
    }

}
